package com.vincce.sport.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.Player;
import com.vincce.sport.entity.School;
import com.vincce.sport.entity.SysUser;
import com.vincce.sport.entity.Team;
import com.vincce.sport.mapper.PlayerMapper;
import com.vincce.sport.mapper.SchoolMapper;
import com.vincce.sport.mapper.TeamMapper;


@Controller
@RequestMapping("/player")
public class PlayerController extends BaseController{
	
	@Resource
	private TeamMapper teamMapper;
	@Resource
	private PlayerMapper playerMapper;
	@Resource
	private SchoolMapper schoolMapper;
	
	@RequestMapping("/palyerList")
	public String queryPlayerByPage(Model model,Page<Player> page,Player player){
		Map<String, Object> filter = new HashMap<String, Object>();
		Map<String, Object> param = new HashMap<String, Object>();
		
		if(player.getName() != null && !player.getName().equals("")){
	            filter.put("name", player.getName());
	    }
		if(player.getTeamId() != null && !player.getTeamId().equals("")){
            filter.put("teamId", player.getTeamId());
        }
		//数据权限过滤
		model.addAttribute("role",0);
		SysUser user = getCurrentUser();
//		if(user!=null){
//			if(user.getTeamId()!=null){
//				filter.put("teamId", user.getTeamId());
//				param.put("id", user.getTeamId());
//				model.addAttribute("roleId",2);
//			}
//		}
        if(user!=null){

            if(user.getRoleId()==2){
                if(user.getTeamId()!=null){
                    filter.put("id", user.getTeamId());
                    model.addAttribute("role",2);
                }
            }

        }
		
		page.setFilter(filter);
		page.setTotal(playerMapper.queryPalyerByCount(page.getFilter()));
		page.setResult(replace(playerMapper.queryPlayerByPage(page)));
		List<School> schoolList = null;
		List<Team> teamList = teamMapper.queryTeam(param);
		if(teamList!=null && teamList.size()==1){
			param = new HashMap<String, Object>();
			param.put("schoolId", teamList.get(0).getSchoolId());
			schoolList = schoolMapper.querySchoolById(param);
		} else{
			schoolList = schoolMapper.queryBySchoolAll();
		}
		model.addAttribute("teamList",teamList);
		model.addAttribute("player",player);
		model.addAttribute("schoolList",schoolList);
		model.addAttribute("page",page);
		return "/backstage/playerList";
	}
	
	
	/**
	 * 图片路径替换
	 * @param
	 * @return
	 */
	public List<Player> replace(List<Player> imgTempList){
		if(imgTempList!=null && imgTempList.size()>0){
			for(Player itl:imgTempList){
				itl.setUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+itl.getUrl(), "ori"));
			}
		}
		return imgTempList;
	}
	
	/**
	 * 新增修改
	 * @param model
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/addOrUpdatePlayer")
	@ResponseBody
	public String addOrUpdatePlayer(Model model,Player player, @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws IOException{
		Long count=0L;
		
		
        Map<String, Object> result = new HashMap<String, Object>();
        SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
        if(CheckUtil.isEmpty(player.getId())){
        	if (file != null && !file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
                } else {
                    obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                    if (obj.statusCode == 200) {
                    	
                    	String path = obj.info.replaceAll("\\\\", "/");
                    	result.put("img", String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+path, "ori"));
                    	//result.put("imgPath", path);
                    	player.setUrl(path);
                    	player.setCreateUser(getCurrentUser().getId().intValue());
                    	player.setCreateTime(new Date());
                    	player.setUpdateTime(new Date());
                    	player.setUpdateUser(getCurrentUser().getId().intValue());
                    	count=playerMapper.insertPalyer(player);
                    	
                    }
                }
            } else{
            	result.put("msg","请选择文件!");
                result.put("suc", false);
            }
        	
        	
        }else{
        	
        	if (file != null && !file.isEmpty()) {
            	String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
				}else{
					obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
	                if (obj.statusCode == 200) {
	                	String path= obj.info.replaceAll("\\\\", "/");
	                	player.setUrl(path);
	                	player.setUpdateTime(new Date());
	                	player.setUpdateUser(getCurrentUser().getId().intValue());
	                	count = playerMapper.updatePalyer(player);
	                }
				}
            } else {
            	player.setUpdateTime(new Date());
            	player.setUpdateUser(getCurrentUser().getId().intValue());
            	count = playerMapper.updatePalyer(player);
            }
        }
        
        
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}
	
	
	/**
	 * 根据ID删除
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteById")
	@ResponseBody
	public String deleteById(Model model,Integer id){
		Boolean flag=false;
		Integer count=playerMapper.deleteById(id);
		flag=count>0?true:false;
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("suc", flag);
        return JSON.toJSONString(result);
	}

	@RequestMapping("/queryPlayerByTeamId")
	@ResponseBody
	public String queryPlayerByTeamId(Model model, Long teamId){
		Map<String, Object> result = new HashMap<String, Object>();
		if(CheckUtil.isEmpty(teamId)){
			result.put("suc", false);
			result.put("msg", "球队id为空");
			return JSON.toJSONString(result);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("teamId", teamId);
		List<Player> list = playerMapper.queryPlayerByTeamId(map);
		result.put("suc", true);
		result.put("msg", "成功");
		result.put("playerList", list);
		return JSON.toJSONString(result);
	}

}
